package com.lsw.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 点击EditText以外的区域或者控件隐藏软键盘
 * 
 * @author 有客云
 * 
 */
@SuppressLint("ClickableViewAccessibility")
public class HideSoftKeyboardUtil {
	public static Activity activity;

	// 隐藏软键盘的工具类方法
	public static void hideSoftKeyboard(Activity activity) {
		InputMethodManager imm = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		// if (activity.getCurrentFocus().getWindowToken()!= null) { //一直是true
		// // imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
		// // InputMethodManager.HIDE_NOT_ALWAYS);
		if (activity.getCurrentFocus() != null) {
			imm.hideSoftInputFromWindow(activity.getCurrentFocus()
					.getWindowToken(), 0);
		}

	}

	/**
	 * 找到根布局，然后让根布局自动找到其子组件，再递归注册监听器
	 * 
	 * @param view
	 *            就是当前页面的根部局（需要给根部局一个ID 在.java文件里面findViewById（R.id.根部局ID））
	 * @param activity1
	 *            当前activity
	 */
	public static void setupUI(View view, final Activity activity1) {
		activity = activity1;
		if (!(view instanceof EditText)) {
			view.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					try {
						hideSoftKeyboard(activity);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return false;
				}
			});
		}
		if (view instanceof ViewGroup) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				View inner = ((ViewGroup) view).getChildAt(i);
				setupUI(inner, activity);
			}
		}
	}

	// //隐藏软键盘的工具类方法
	// public static void hideSoftKeyboard(Activity activity) {
	// InputMethodManager inputMethodManager = (InputMethodManager)
	// activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
	// inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
	// 0);
	// }
	// /**
	// * 找到根布局，然后让根布局自动找到其子组件，再递归注册监听器
	// * @param view
	// */
	// public void setupUI(View view) {
	// if(!(view instanceof EditText)) {
	// view.setOnTouchListener(new OnTouchListener() {
	// @Override
	// public boolean onTouch(View v, MotionEvent event) {
	// hideSoftKeyboard(HomeQueRenDingdanActivity.this);
	// return false;
	// }
	// });
	// }
	// if(view instanceof ViewGroup){
	// for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
	// View inner=((ViewGroup)view).getChildAt(i);
	// setupUI(inner);
	// }
	// }
	// }

}
